﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Application.Email;
using YunSpace.Application.SystemManage;
using YunSpace.Application.WorkFlow;
using YunSpace.Core;
using YunSpace.Data;
using YunSpace.Domain.ViewModel.OrderFlowManage;
using YunSpace.Domain.Entity;
using YunSpace.Domain.Entity.OrderFlowManage;
using YunSpace.Domain.Entity.SiteLibraryManage;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Domain.IRepository.OrderFlowManage;
using YunSpace.Domain.ViewModel.ClientManager;
using YunSpace.Domain.ViewModel.OrderFlowManage;
using YunSpace.Domain.ViewModel.SiteMgr;
using YunSpace.Domain.ViewModel.System;
using YunSpace.Repository.OrderFlowManage;

namespace YunSpace.Application.OrderFlowManage
{
    public class OrderCheckApp
    {
        private ItemsDetailApp itemsDetailApp = new ItemsDetailApp();
        private IClientOrderRepository orderRepository = new ClientOrderRepository();
        private IClientOrderrecommendRepository recommendRepository = new ClientOrderrecommendRepository();
        private IMessageNoticeRepository mesRepository = new MessageNoticeRepository();
        private ICheckRecordRepository checkRepository = new CheckRecordRepository();
        private IClientOrdertakelookDetailRepository clientOrdertakelookDetailRepository = new ClientOrdertakelookDetailRepository();
        private IClientOrdertakelookRepository clientOrdertakelookRepository = new ClientOrdertakelookRepository();
        private IClientOrderintentionRepository intentionRepository = new ClientOrderintentionRepository();
        private IClientOrderPriceDetailRepository orderPriceDetailRepository = new ClientOrderPriceDetailRepository();
        private IClientOrderreserveRepository clientOrderReserveRepository = new ClientOrderreserveRepository();
        private IClientOrdersigncontractRepository clientOrderSignContractRepository = new ClientOrdersigncontractRepository();
        private ISiteClientOrderMappingRepository mappingRepository = new SiteClientOrderMappingRepository();

        public List<OrderCheckViewModel> GetOrderCheckList(Pagination pagination, string queryJson, string userId)
        {
            List<OrderCheckViewModel> result = new List<OrderCheckViewModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_No,a.F_FlowId,a.F_OrderId,a.F_ApplyType ApplyTypeNo,a.F_ApplyType,a.F_CheckContent,b.F_Id F_CheckUserId,b.F_RealName CheckUserName,b.F_DepartmentId CheckDepartment,
                            c.F_RealName ApplyUserName,c.F_DepartmentId ApplyDepartment,a.F_CreatorTime,a.F_State,a.F_State orderF_State from Sys_CheckRecord a
                            inner join Sys_User b on a.F_CheckUserId=b.F_Id
                            inner join Sys_User c on a.F_ApplyUserId=c.F_Id where 1=1 {0} {1} {2} {3} {4} order by a.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ApplyUserId", queryParam["F_ApplyUserId"]),
                    new MySqlParameter("@F_ApplyType", queryParam["F_ApplyType"]),
                    new MySqlParameter("@F_CreatorTime", queryParam["F_CreatorTime"]),
                    new MySqlParameter("@F_State", queryParam["F_State"]),
                    new MySqlParameter("@F_CheckUserId", userId.IsEmpty()?"":userId)
                };
                strSql = string.Format(strSql, queryParam["F_ApplyUserId"].IsEmpty() ? "" : " and a.F_ApplyUserId=@F_ApplyUserId",
                    queryParam["F_ApplyType"].IsEmpty() ? "" : " and a.F_ApplyType=@F_ApplyType",
                    queryParam["F_CreatorTime"].IsEmpty() ? "" : " and a.F_CreatorTime>=@F_CreatorTime",
                    userId.IsEmpty() ? "" : " and a.F_CheckUserId=@F_CheckUserId",
                    queryParam["F_State"].IsEmpty() ? "" : " and a.F_State=@F_State"
                    );
                result = db.FindList<OrderCheckViewModel>(strSql, parameter, pagination);
            }
            return result;
        }

        public List<HighSeaCheckModel> GetHighSeaCheckList(Pagination pagination)
        {
            List<HighSeaCheckModel> result = new List<HighSeaCheckModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,b.F_Id F_DemandId,d.F_Id F_ClientId,a.F_Id as F_Ids,b.F_Source,d.F_ClientName,b.F_ActivityTheme,b.F_ActivityType,b.F_DemandCash,
                            date_format(b.F_ActivityStartDate,'%Y-%m-%d') F_ActivityStartDate,date_format(b.F_ActivityEndDate,'%Y-%m-%d') F_ActivityEndDate
                            ,b.F_SiteType,c.F_RealName,a.F_CreatorTime from Site_Client_Order a 
                            inner join Site_Clients_ProjectByDemand b on a.F_DemandId=b.F_Id
                            inner join Site_Clients d on d.F_Id=b.F_ClientId
                            inner join Sys_User c on a.F_FlowUserId=c.F_Id where a.F_IsCheck=0";
                DbParameter[] parameter = { };
                result = db.FindList<HighSeaCheckModel>(strSql, parameter, pagination);
            }
            return result;
        }
        /// <summary>
        /// 统计-首页数量统计
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public HomeViewModel GetOrderCheckCount(string userId)
        {
            HomeViewModel result = new HomeViewModel();
            using (var db = new RepositoryBase())
            {
                var stime = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
                var etime = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);

                //首页五项数据获取
                var strSql1 = $@"select DemandOrderCount,OrderIncomeCountByUserId,DemandCount,OrderCount,OrderIncomeCount from
                                (select count(1)DemandOrderCount,1 as id from Site_Client_Order sco where sco.F_FlowUserId='{ userId} ' and sco.F_OrderState between 1 and 7 ) a 
                                inner join (select sum(scou.F_SpendCash)OrderIncomeCountByUserId,1 as id from Site_Client_Order so 
                                inner join Sys_CheckRecord sc on sc.F_OrderId=so.F_Id and sc.F_ApplyType=6 and sc.F_State=1 
                                inner join(select sum(su.F_SpendCash)F_SpendCash,su.F_No from Site_Client_OrderUsing su group by su.F_No) scou on scou.F_No = sc.F_No 
                                where so.F_OrderState=8 and  so.F_FlowUserId='{ userId } ')  b on a.id=b.id
                                inner join (select count(1)DemandCount, 1 as id from Site_Clients_ProjectByDemand scp where scp.F_CreatorTime between '{ stime}' and '{ etime}') c on b.id=c.id 
                                inner join (select count(1)OrderCount, 1 as id from Site_Client_Order sco where sco.F_CreatorTime  between '{ stime}' and '{ etime}' ) d on d.id=c.id 
                                inner join(select sum(scou.F_SpendCash) as OrderIncomeCount, 1 as id from Site_Client_Order so 
                                inner join Sys_CheckRecord sc on sc.F_OrderId=so.F_Id and sc.F_ApplyType=6 and sc.F_State=1 
                                inner join(select sum(su.F_SpendCash)F_SpendCash,su.F_No from Site_Client_OrderUsing su group by su.F_No) scou on scou.F_No = sc.F_No where so.F_OrderState=8) e on e.id= d.id";
                //统计销售部的业绩情况
                var strSql2 = @"select UserName,sum(Income) Income from(select u.F_RealName UserName,b.OrderIncomeCount Income from Sys_User u 
                                left join (select a.F_SiteRent+a.F_MatingRent as OrderIncomeCount,b.F_FlowUserId from Site_Client_OrderBookRecord a 
                                inner join Site_Client_Order b on a.F_OrderId=b.F_Id where a.F_SigningDate>=DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1 DAY) 
                                and a.F_SigningDate<=concat(YEAR(now()),'-12-31')) as b on b.F_FlowUserId = u.F_Id 
                                where u.F_DepartmentId in ('5c60c965-8404-452e-8628-b00ee3714e95','01068646-a03a-483e-95fd-41c601552b75','32bc6d4a-3da0-4583-b267-0d751d94bde3','53cca542-a693-4a51-b66e-1ce5daa59b21') 
                                and u.F_RoleId in ('8d092152-9885-4d53-9fbd-8791191e5098','3b3771c6-e7f4-4fba-aae0-9dd5f0fae3cf','ac595b87-77fe-4e56-8e50-4cea28e11f7c') 
                                and u.F_EnabledMark=1 and u.F_Id not in('95dbacb1-0d5c-11e8-bc3f-00163e00446b')) b group by UserName";

                var strSql3 = @"select item.F_ItemName,count(1) as counts from SL_Site s inner join (
                                select si.F_ItemName,si.F_ItemCode from Sys_Items i inner join Sys_ItemsDetail si on si.F_ItemId = i.F_Id where i.F_EnCode = 'SiteType') item
                                    on item.F_ItemCode = s.site_type
                                where s.state = 1 group by s.site_type ";


                var data1 = db.FindList<GetStatisticalCount>(strSql1).FirstOrDefault();
                var data2 = db.FindList<GetUserIncome>(strSql2);
                var data3 = db.FindList<SiteTypeCount>(strSql3);
                result.StatisticalCount = data1;
                result.UsersIncome = data2;
                result.SiteType = data3;
            }
            return result;
        }

        public List<OrderCheckViewModel> GetMyApplyGridData(Pagination pagination, string queryJson, string userId)
        {
            List<OrderCheckViewModel> result = new List<OrderCheckViewModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select  
                                a.F_Id,a.F_No,a.F_OrderId,a.F_ApplyType ApplyTypeNo,
                                a.F_ApplyType,a.F_CheckContent,
                                b.F_RealName CheckUserName,b.F_DepartmentId CheckDepartment,
                                c.F_RealName ApplyUserName,c.F_DepartmentId ApplyDepartment,
                                a.F_CreatorTime,a.F_State,
                                a.F_CheckUserId,a.F_State orderF_State,a.F_FlowId                               
                            from Sys_CheckRecord a
                            inner join Sys_User b on a.F_CheckUserId=b.F_Id
                            inner join Sys_User c on a.F_ApplyUserId=c.F_Id where 1=1 {0} {1} {2} {3} order by a.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_ApplyType", queryParam["F_ApplyType"]),
                    new MySqlParameter("@F_CreatorTime", queryParam["F_CreatorTime"]),
                    new MySqlParameter("@F_State", queryParam["F_State"]),
                    new MySqlParameter("@F_ApplyUserId", userId.IsEmpty()?"":userId)
                };
                strSql = string.Format(strSql,
                    queryParam["F_ApplyType"].IsEmpty() ? "" : " and a.F_ApplyType=@F_ApplyType",
                    queryParam["F_CreatorTime"].IsEmpty() ? "" : " and a.F_CreatorTime>=@F_CreatorTime",
                    userId.IsEmpty() ? "" : " and a.F_ApplyUserId=@F_ApplyUserId",
                    queryParam["F_State"].IsEmpty() ? "" : " and a.F_State=@F_State"
                    );
                result = db.FindList<OrderCheckViewModel>(strSql, parameter, pagination);
            }
            return result;
        }

        public List<ItemsDetailActionModel> GetItemList(string enCode)
        {
            return itemsDetailApp.GetItemList(enCode);
        }

        public List<OrganizeEntity> GetOrganizeList()
        {
            List<OrganizeEntity> result = CacheFactory.Cache().Get("Organize") as List<OrganizeEntity>;
            if (result == null)
            {
                using (var db = new RepositoryBase())
                {
                    var strSql = @"select * from Sys_Organize a where a.F_CategoryId='Department'";
                    result = db.FindList<OrganizeEntity>(strSql);
                    CacheFactory.Cache().Insert("Organize", result);
                }
            }
            return result;
        }

        public List<UserEntity> GetUserList()
        {
            List<UserEntity> result = CacheFactory.Cache().Get("User") as List<UserEntity>;
            if (result == null)
            {
                using (var db = new RepositoryBase())
                {
                    var strSql = @"select * from Sys_User";
                    result = db.FindList<UserEntity>(strSql);
                    CacheFactory.Cache().Insert("User", result);
                }
            }
            return result;
        }

        public List<OrderIntentionModel> GetOrderIntentionModel(Pagination pagination, string queryJson)
        {
            List<OrderIntentionModel> result = new List<OrderIntentionModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_OrderId,b.title SiteName,b.city_id City,f.F_Reason,f.F_Remark,c.title SpaceName,date_format(a.F_StartDate, '%Y-%m-%d') F_StartDate,date_format(a.F_EndDate, '%Y-%m-%d') F_EndDate,e.F_RealName,ifnull(f.F_State,0) F_State,d.F_CreatorTime 
                                from Site_Client_OrderIntention a
                                inner join SL_Site b on a.F_SiteId=b.F_Id and b.state=1
                                inner join SL_Space c on a.F_SpaceId=c.F_Id and c.state=1
                                inner join Sys_CheckRecord d on a.F_OrderId=d.F_OrderId and a.F_No=d.F_No
                                inner join Sys_User e on d.F_ApplyUserId=e.F_Id
                                left join Site_Client_OrderMapping f on f.F_DetailId=a.F_Id and f.F_ApplyType=d.F_ApplyType
                                where 1=1 and d.F_ApplyType=3 {0} {1} order by a.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_OrderId", queryParam["F_OrderId"]),
                    new MySqlParameter("@F_CheckUserId", queryParam["F_CheckUserId"])
                };
                strSql = string.Format(strSql, queryParam["F_OrderId"].IsEmpty() ? "" : " and a.F_OrderId=@F_OrderId",
                    queryParam["F_CheckUserId"].IsEmpty() ? "" : " and d.F_CheckUserId=@F_CheckUserId"
                    );
                result = db.FindList<OrderIntentionModel>(strSql, parameter, pagination);
            }
            return result;
        }

        public List<OrderPriceCheckModel> GetCheckPrice(string queryJson)
        {
            List<OrderPriceCheckModel> result = new List<OrderPriceCheckModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_OrderId,b.F_Id F_SiteId,b.title SiteName,b.city_id City,c.F_Id F_SpaceId,c.title SpaceName,d.F_ApplyType,c.F_MarketPrice,c.F_YunPrice,c.F_MarketPrice F_SalePrice,
                                c.F_Units,c.area F_Area,date_format(a.F_StartDate, '%Y-%m-%d') F_StartDate,date_format(a.F_EndDate, '%Y-%m-%d') F_EndDate,
                                a.F_CreatorTime,to_days(a.F_EndDate)-to_days(a.F_StartDate)+1 F_Days,
                                d.F_State checkState,f.F_ServiceCode,f.F_ServiceCode,f.F_Num,f.F_Price,f.F_PriceUnit,f.F_Id F_DetailId,h.F_ActivityTheme,h.F_ActivityCityId
                                from Site_Client_OrderPriceTalks a 
                                inner join SL_Site b on a.F_SiteId=b.F_Id and b.state=1
                                inner join SL_Space c on a.F_SpaceId=c.F_Id and c.state=1
                                inner join Sys_CheckRecord d on a.F_OrderId=d.F_OrderId and a.F_No=d.F_No
                                inner join Site_Client_Order g on g.F_Id=a.F_OrderId
                                inner join Site_Clients_ProjectByDemand h on h.F_Id=g.F_DemandId
                                left join Site_Client_OrderIntentionDetail f on a.F_SiteId=f.F_SiteId and a.F_SpaceId=f.F_SpaceId and a.F_OrderId=f.F_OrderId
                                where 1=1 and d.F_ApplyType=3 {0} {1} {2} order by a.F_SpaceId desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_OrderId", queryParam["F_OrderId"]),
                    new MySqlParameter("@F_CheckUserId", queryParam["F_CheckUserId"]),
                    new MySqlParameter("@F_No", queryParam["F_No"]),
                };
                strSql = string.Format(strSql, queryParam["F_OrderId"].IsEmpty() ? "" : " and a.F_OrderId=@F_OrderId",
                    queryParam["F_CheckUserId"].IsEmpty() ? "" : " and d.F_CheckUserId=@F_CheckUserId",
                    queryParam["F_No"].IsEmpty() ? "" : " and d.F_No=@F_No"
                    );
                result = db.FindList<OrderPriceCheckModel>(strSql, parameter);
            }
            return result;
        }

        public List<OrderRecommendCheckModel> GetCheckSchedule(Pagination pagination, string queryJson)
        {
            List<OrderRecommendCheckModel> result = new List<OrderRecommendCheckModel>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_OrderId,b.title SiteName,b.city_id City,c.title SpaceName,date_format(a.F_StartDate, '%Y-%m-%d') F_StartDate,
                                date_format(a.F_EndDate, '%Y-%m-%d') F_EndDate,e.F_RealName,ifnull(f.F_State,0) F_State,f.F_Reason,f.F_Remark,d.F_CreatorTime,
                                concat_ws('','yunspace价格:',a.F_YunPrice,',市场价:',a.F_MarketPrice,',单位:',h.F_ItemName) remark
                                from Site_Client_OrderRecommend a
                                inner join SL_Site b on a.F_SiteId=b.F_Id and b.state=1
                                inner join SL_Space c on a.F_SpaceId=c.F_Id and c.state=1
                                inner join Sys_CheckRecord d on a.F_OrderId=d.F_OrderId  and a.F_No=d.F_No
                                inner join Sys_User e on d.F_ApplyUserId=e.F_Id
                                left join Site_Client_OrderMapping f on a.F_Id=f.F_DetailId and f.F_ApplyType=d.F_ApplyType and f.F_CheckUserId=d.F_CheckUserId
                                left join (
	 	                             select h.* from Sys_Items t
 	 	                             inner join Sys_ItemsDetail h on t.F_Id=h.F_ItemId
 	 	                             where t.F_EnCode='units'
	                            ) h on a.F_Units=h.F_ItemCode
                                where 1=1 and d.F_ApplyType=1 {0} {1} {2} {3} order by a.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_OrderId", queryParam["F_OrderId"]),
                    new MySqlParameter("@F_CheckUserId", queryParam["F_CheckUserId"]),
                    new MySqlParameter("@F_Id", queryParam["F_CheckId"]),
                    new MySqlParameter("@F_No", queryParam["F_No"])
                };
                strSql = string.Format(strSql, queryParam["F_OrderId"].IsEmpty() ? "" : " and a.F_OrderId=@F_OrderId",
                    queryParam["F_CheckUserId"].IsEmpty() ? "" : " and d.F_CheckUserId=@F_CheckUserId",
                    queryParam["F_CheckId"].IsEmpty() ? "" : " and d.F_Id=@F_Id",
                    queryParam["F_No"].IsEmpty() ? "" : " and d.F_No=@F_No"
                    );
                result = db.FindList<OrderRecommendCheckModel>(strSql, parameter, pagination);
            }
            return result;
        }

        public void CheckOrderIntention(string F_Id, int State, string F_CheckId, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            ClientOrderintentionEntity entity = intentionRepository.FindEntity(F_Id);
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            if (entity != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    entity.F_State = State;
                    entity.Modify(F_Id);
                    db.Update<ClientOrderintentionEntity>(entity);

                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = ApplyType;
                    mappingEntity.F_DetailId = F_Id;
                    mappingEntity.F_State = State;
                    mappingEntity.F_CheckUserId = F_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                    MessageNoticeEntity message = new MessageNoticeEntity();
                    message.Create();
                    message.F_IsRead = 0;
                    message.F_MessageType = 1;
                    message.F_MessageWay = 1;
                    message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                    if (State == 1)
                    {
                        message.F_MessageContent = "场地有档期";

                    }
                    else
                    {
                        message.F_MessageContent = "场地无档期";
                    }
                    db.Insert<MessageNoticeEntity>(message);
                    db.Commit();
                }

                List<ClientOrderintentionEntity> intentionList = GetClientOrderintentionEntity(checkEntity.F_OrderId, F_CheckId);
                var intentionRecord = (from p in intentionList where p.F_State == 0 select p).ToList();
                if (intentionRecord.Count == 0)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        var noRecord = (from p in intentionList where p.F_State == 2 select p).ToList();
                        MessageNoticeEntity message = new MessageNoticeEntity();
                        message.Create();
                        message.F_IsRead = 0;
                        message.F_MessageType = 1;
                        message.F_MessageWay = 1;
                        message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                        if (intentionList.Count > 0 && noRecord.Count > 0 && noRecord.Count == intentionRecord.Count)
                        {
                            checkEntity.F_State = 0;
                            message.F_MessageContent = "场地意向审核驳回";
                        }
                        else
                        {
                            checkEntity.F_State = 1;
                            message.F_MessageContent = "场地意向审核通过";
                        }

                        db.Insert<MessageNoticeEntity>(message);

                        checkEntity.Modify(F_CheckId);
                        db.Update<CheckRecordEntity>(checkEntity);
                        db.Commit();
                    }

                    OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState);
                }
            }

            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, State);
        }

        public SpaceEntity GetSitePrice(string F_Id)
        {
            using (var db = new RepositoryBase())
            {
                ClientOrderrecommendEntity entity = recommendRepository.FindEntity(F_Id);
                var SpaceId = entity.F_SpaceId;
                var Space=db.FindEntity<SpaceEntity>(SpaceId);
                return Space;
            }
        }

        public void SetSchedule(string F_Id, int State, string F_CheckId, string F_FlowId, int ApplyType, string F_CheckUserId,string MPrice,string YPrice,string unit)
        {
            ClientOrderrecommendEntity entity = recommendRepository.FindEntity(F_Id);
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            if (entity != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    decimal MarketPrice = 0, YUNPrice = 0;
                    decimal.TryParse(MPrice, out MarketPrice);
                    decimal.TryParse(YPrice, out YUNPrice);

                    entity.F_MarketPrice = MarketPrice;
                    entity.F_YunPrice = YUNPrice;
                    entity.F_Units = unit;
                    entity.F_State = State;
                    entity.Modify(F_Id);
                    db.Update<ClientOrderrecommendEntity>(entity);

                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = ApplyType;
                    mappingEntity.F_DetailId = F_Id;
                    mappingEntity.F_State = State;
                    mappingEntity.F_CheckUserId = F_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                    MessageNoticeEntity message = new MessageNoticeEntity();
                    message.Create();
                    message.F_IsRead = 0;
                    message.F_MessageType = 1;
                    message.F_MessageWay = 1;
                    message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                    if (State == 1)
                    {
                        message.F_MessageContent = "场地有档期";

                    }
                    else
                    {
                        message.F_MessageContent = "场地无档期";
                    }
                    db.Insert<MessageNoticeEntity>(message);
                    db.Commit();
                }

                List<ClientOrderrecommendEntity> recommList = GetClientOrderrecommendEntity(checkEntity.F_OrderId, entity.F_No);
                var recommRecord = (from p in recommList where p.F_State == 0 select p).ToList();
                if (recommRecord.Count == 0)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        var noRecord = (from p in recommList where p.F_State == 2 select p).ToList();
                        MessageNoticeEntity message = new MessageNoticeEntity();
                        message.Create();
                        message.F_IsRead = 0;
                        message.F_MessageType = 1;
                        message.F_MessageWay = 1;
                        message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                        if (recommList.Count > 0 && noRecord.Count > 0 && noRecord.Count == recommList.Count)
                        {
                            checkEntity.F_State = 0;
                            message.F_MessageContent = "审核驳回";
                        }
                        else
                        {
                            checkEntity.F_State = 1;
                            message.F_MessageContent = "审核通过";
                        }

                        db.Insert<MessageNoticeEntity>(message);

                        checkEntity.Modify(F_CheckId);
                        db.Update<CheckRecordEntity>(checkEntity);
                        db.Commit();
                    }
                    OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState);
                }
                SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, State);
            }
        }

        public List<ClientOrderintentionEntity> GetClientOrderintentionEntity(string F_OrderId, string F_CheckId)
        {
            List<ClientOrderintentionEntity> result = new List<ClientOrderintentionEntity>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                string strSql = "select * from Site_Client_OrderIntention a where a.F_OrderId=@F_OrderId and a.F_Id=@F_Id";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_OrderId", F_OrderId),
                    new MySqlParameter("@F_Id", F_CheckId)
                };
                result = db.FindList<ClientOrderintentionEntity>(strSql, parameter);
            }
            return result;
        }

        public List<ClientOrderrecommendEntity> GetClientOrderrecommendEntity(string F_OrderId, string F_No)
        {
            List<ClientOrderrecommendEntity> result = new List<ClientOrderrecommendEntity>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                string strSql = "select * from Site_Client_OrderRecommend a where a.F_OrderId=@F_OrderId and a.F_No=@F_No";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_OrderId", F_OrderId),
                    new MySqlParameter("@F_No", F_No)
                };
                result = db.FindList<ClientOrderrecommendEntity>(strSql, parameter);
            }
            return result;
        }

        public void SubmitFormIntention(string F_Id, string F_CheckId, int F_Reason, string F_Remark, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            ClientOrderintentionEntity entity = intentionRepository.FindEntity(F_Id);
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            if (entity != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = ApplyType;
                    mappingEntity.F_DetailId = F_Id;
                    mappingEntity.F_State = 2;
                    mappingEntity.F_CheckUserId = F_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                    MessageNoticeEntity message = new MessageNoticeEntity();
                    message.Create();
                    message.F_IsRead = 0;
                    message.F_MessageType = 1;
                    message.F_MessageWay = 1;
                    message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                    message.F_MessageContent = "场地无档期";
                    db.Insert<MessageNoticeEntity>(message);

                    entity.F_State = 2;
                    entity.F_Reason = F_Reason;
                    entity.F_Remark = F_Remark;

                    entity.Modify(F_Id);
                    db.Update<ClientOrderintentionEntity>(entity);
                    db.Commit();
                }
            }

            List<ClientOrderintentionEntity> intentionList = GetClientOrderintentionEntity(checkEntity.F_OrderId, F_CheckId);
            var intentionRecord = (from p in intentionList where p.F_State == 0 select p).ToList();
            if (intentionRecord.Count == 0)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var noRecord = (from p in intentionList where p.F_State == 2 select p).ToList();
                    MessageNoticeEntity message = new MessageNoticeEntity();
                    message.Create();
                    message.F_IsRead = 0;
                    message.F_MessageType = 1;
                    message.F_MessageWay = 1;
                    message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                    if (noRecord.Count == intentionList.Count)
                    {
                        checkEntity.F_State = 0;
                        message.F_MessageContent = "意向场地审核驳回";
                    }
                    else
                    {
                        checkEntity.F_State = 1;
                        message.F_MessageContent = "意向场地审核通过";
                    }

                    db.Insert<MessageNoticeEntity>(message);

                    checkEntity.Modify(F_CheckId);
                    db.Update<CheckRecordEntity>(checkEntity);
                    db.Commit();
                }
                OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState);
            }

            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, 2);
        }

        public void SubmitFormCheck(string F_Id, string F_CheckId, int F_Reason, string F_Remark, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            ClientOrderrecommendEntity entity = recommendRepository.FindEntity(F_Id);
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            if (entity != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = ApplyType;
                    mappingEntity.F_DetailId = F_Id;
                    mappingEntity.F_State = 2;
                    mappingEntity.F_Reason = F_Reason;
                    mappingEntity.F_Remark = F_Remark;
                    mappingEntity.F_CheckUserId = F_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                    MessageNoticeEntity message = new MessageNoticeEntity();
                    message.Create();
                    message.F_IsRead = 0;
                    message.F_MessageType = 1;
                    message.F_MessageWay = 1;
                    message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                    message.F_MessageContent = "场地无档期";
                    db.Insert<MessageNoticeEntity>(message);

                    entity.F_State = 2;
                    entity.F_Reason = F_Reason;
                    entity.F_Remark = F_Remark;
                    entity.Modify(F_Id);
                    db.Update<ClientOrderrecommendEntity>(entity);
                    db.Commit();
                }
            }

            List<ClientOrderrecommendEntity> recommList = GetClientOrderrecommendEntity(checkEntity.F_OrderId, entity.F_No);
            var recommRecord = (from p in recommList where p.F_State == 0 select p).ToList();
            if (recommRecord.Count == 0)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var noRecord = (from p in recommList where p.F_State == 2 select p).ToList();
                    MessageNoticeEntity message = new MessageNoticeEntity();
                    message.Create();
                    message.F_IsRead = 0;
                    message.F_MessageType = 1;
                    message.F_MessageWay = 1;
                    message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                    if (recommList.Count > 0 && noRecord.Count > 0 && noRecord.Count == recommList.Count)
                    {
                        checkEntity.F_State = 0;
                        message.F_MessageContent = "审核驳回";
                    }
                    else
                    {
                        checkEntity.F_State = 1;
                        message.F_MessageContent = "审核通过";
                    }

                    db.Insert<MessageNoticeEntity>(message);

                    checkEntity.Modify(F_CheckId);
                    db.Update<CheckRecordEntity>(checkEntity);
                    db.Commit();
                }
                OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState);
            }

            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, 2);
        }

        public void CheckOrder(string F_Id, int State)
        {
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_Id);
            using (var db = new RepositoryBase().BeginTrans())
            {
                MessageNoticeEntity message = new MessageNoticeEntity();
                message.Create();
                message.F_IsRead = 0;
                message.F_MessageType = 1;
                message.F_MessageWay = 1;
                message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                if (State == 1)
                {
                    message.F_MessageContent = "审核通过";
                }
                else
                {
                    message.F_MessageContent = "审核驳回";
                }

                db.Insert<MessageNoticeEntity>(message);

                checkEntity.F_State = State;
                checkEntity.Modify(F_Id);
                db.Update<CheckRecordEntity>(checkEntity);
                db.Commit();
            }
        }

        #region 场地报价单
        public List<OrderPriceCreateModel> GetOrderPriceInfos(string F_Ids)
        {
            List<OrderPriceCreateModel> result = new List<OrderPriceCreateModel>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                string strSql = @"select c.F_Id,b.F_ActivityTheme,b.F_ActivityCityId,DATE_FORMAT(b.F_ActivityStartDate,'%Y-%m-%d') F_ActivityStartDate,DATE_FORMAT(b.F_ActivityEndDate,'%Y-%m-%d') F_ActivityEndDate,
                                datediff(b.F_ActivityEndDate, b.F_ActivityStartDate) Quantity,d.F_Id siteId,d.title SiteName,e.F_Id spaceId,e.title SpaceName,
                                  e.area,e.F_MarketPrice,e.F_YunPrice,e.F_Units,datediff(b.F_ActivityEndDate, b.F_ActivityStartDate) * e.F_YunPrice totalPrice
                                from Site_Client_Order a
                                inner join Site_Clients_ProjectByDemand b on a.F_DemandId = b.F_Id
                                inner join Site_Client_OrderPriceTalks c on a.F_Id = c.F_OrderId
                                inner join SL_Site d on c.F_SiteId = d.F_Id and d.state=1 
                                inner join SL_Space e on c.F_SpaceId = e.F_Id and e.state=1                              
                                where 1=1 and c.F_Id in (" + string.Join(",", F_Ids.Split(',').Select(p => string.Format("'{0}'", p))) + ")";
                result = db.FindList<OrderPriceCreateModel>(strSql);
            }
            return result;
        }

        public List<OrderPriceViewModel> GetOrderPriceView(string OrderId, string F_No)
        {
            List<OrderPriceViewModel> result = new List<OrderPriceViewModel>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                string strSql = @"select a.F_Id,b.title F_SiteName,c.title F_SpaceName,b.F_Id F_SpaceId,a.F_ActivityName,a.F_ActivityCity,a.F_ActivityDate,a.F_FeeType,
                                a.F_Unit,a.F_MarketPrice,a.F_YunPrice,a.F_SpaceArea,a.F_Quantity,a.F_TotalPrice,
                                ifnull(a.F_SalePrice,0) F_SalePrice
                                from Site_Client_OrderPriceDetail a
                                inner join SL_Site b on a.F_SiteId=b.F_Id and b.state=1
                                inner join SL_Space c on a.F_SpaceId=c.F_Id and c.state=1
                                where 1=1 and a.F_OrderId='" + OrderId + "' and a.F_No='" + F_No + "'  order by c.F_Id desc,a.F_FeeType asc";
                result = db.FindList<OrderPriceViewModel>(strSql);
            }
            return result;
        }

        public void InsertOrderPrice(OrderPriceInput priecs, string F_CheckId, string F_OrderId, string F_FlowId, int ApplyType, string F_No)
        {
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            List<string> SiteIds = new List<string>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                for (int i = 0; i < priecs.data.Count; i++)
                {
                    OrderPriceSaveDetail entity = priecs.data[i];
                    ClientOrderPriceDetailEntity detaiEntity = new ClientOrderPriceDetailEntity();
                    detaiEntity.Create();
                    detaiEntity.F_No = F_No;
                    detaiEntity.F_OrderId = entity.F_OrderId;
                    detaiEntity.F_CheckId = entity.F_CheckId;
                    detaiEntity.F_ActivityName = entity.F_ActivityName;
                    detaiEntity.F_ActivityCity = entity.F_ActivityCity;
                    detaiEntity.F_SiteId = entity.F_SiteId;
                    detaiEntity.F_SpaceId = entity.F_SpaceId;
                    detaiEntity.F_ActivityDate = entity.F_ActivityDate;
                    detaiEntity.F_FeeType = entity.F_FeeType;
                    detaiEntity.F_Unit = entity.F_Unit;
                    detaiEntity.F_MarketPrice = entity.F_MarketPrice;
                    detaiEntity.F_YunPrice = entity.F_YunPrice;
                    detaiEntity.F_SalePrice = entity.F_SalePrice;
                    detaiEntity.F_SpaceArea = entity.F_SpaceArea;
                    detaiEntity.F_Quantity = entity.F_Quantity;
                    detaiEntity.F_TotalPrice = entity.F_TotalPrice;
                    db.Insert<ClientOrderPriceDetailEntity>(detaiEntity);
                    SiteIds.Add(entity.F_SiteId);
                }

                MessageNoticeEntity message = new MessageNoticeEntity();
                message.Create();
                message.F_IsRead = 0;
                message.F_MessageType = 1;
                message.F_MessageWay = 1;
                message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                message.F_MessageContent = "意向场地报价单申请审核通过";

                db.Insert<MessageNoticeEntity>(message);

                var result = GetListForOrderintention(F_OrderId, F_No);
                for (int i = 0; i < result.Count; i++)
                {
                    ClientOrderintentionEntity entity = result[i];
                    entity.F_State = 1;
                    entity.Modify(entity.F_Id);
                    db.Update<ClientOrderintentionEntity>(entity);
                }

                checkEntity.F_State = 1;
                checkEntity.Modify(F_CheckId);
                db.Update<CheckRecordEntity>(checkEntity);
                db.Commit();
            }
            OpreationFlowProcess(F_FlowId, ApplyType, F_OrderId, F_CheckId, F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, String.Join(",", SiteIds), 1);
        }

        public List<ClientOrderintentionEntity> GetListForOrderintention(string F_OrderId, string F_No)
        {
            List<ClientOrderintentionEntity> result = new List<ClientOrderintentionEntity>();
            using (var db = new RepositoryBase())
            {
                string sql = "select * from Site_Client_OrderIntention a where a.F_No='" + F_No + "' and a.F_OrderId='" + F_OrderId + "' ";
                result = db.FindList<ClientOrderintentionEntity>(sql);
            }
            return result;
        }

        public List<ClientOrderpricetalksEntity> GetListForOrderpricetalks(string F_OrderId, string F_No)
        {
            List<ClientOrderpricetalksEntity> result = new List<ClientOrderpricetalksEntity>();
            using (var db = new RepositoryBase())
            {
                string sql = "select * from Site_Client_OrderPriceTalks a where a.F_No='" + F_No + "' and a.F_OrderId='" + F_OrderId + "' ";
                result = db.FindList<ClientOrderpricetalksEntity>(sql);
            }
            return result;
        }

        public void EditOrderPrice(string F_Id, decimal F_YunPrice, int F_Quantity, decimal F_TotalPrice)
        {
            ClientOrderPriceDetailEntity detaiEntity = orderPriceDetailRepository.FindEntity(F_Id);
            detaiEntity.F_YunPrice = F_YunPrice;
            detaiEntity.F_Quantity = F_Quantity;
            detaiEntity.F_TotalPrice = F_TotalPrice;
            detaiEntity.Modify(F_Id);
            orderPriceDetailRepository.Update(detaiEntity);
        }

        public List<AreaModel> GetAllCitys()
        {
            List<AreaModel> citys = CacheFactory.Cache().Get("City") as List<AreaModel>;
            if (citys == null)
            {
                using (var db = new RepositoryBase())
                {
                    string strSql = @"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName  from Sys_Area a where a.F_Layers=2";
                    citys = db.FindList<AreaModel>(strSql);
                    CacheFactory.Cache().Insert("City", citys);
                }
            }
            return citys;
        }

        public void CheckUsing(string usingPriceId, int state, string checkId, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            var checkEntity = checkRepository.FindEntity(checkId);
            var message = CreateDefaultMessageNotice(checkEntity.F_ApplyUserId, state == 1 ? "已确认场地预定" : "已驳回");
            string SiteIds = "";
            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                mappingEntity.Create();
                mappingEntity.F_ApplyType = ApplyType;
                mappingEntity.F_DetailId = usingPriceId;
                mappingEntity.F_State = state;
                mappingEntity.F_CheckUserId = F_CheckUserId;
                db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                db.Insert(message);
                checkEntity.F_State = state;
                checkEntity.Modify(checkId);
                db.Update<CheckRecordEntity>(checkEntity);


                string sql = $@"SELECT * FROM Site_Client_OrderReserve T 
                                 WHERE T.F_OrderId='{checkEntity.F_OrderId}' AND T.F_State='1'";
                var ReserveList = db.FindList<ClientOrderreserveEntity>(sql);
                SiteIds = String.Join(",", ReserveList.Select(t => t.F_SiteId));
                db.Commit();
            }
            OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState, String.Join(",", SiteIds), state);
            if (state == 1)
            {
                ClientOrderEntity orderEntity = orderRepository.FindEntity(checkEntity.F_OrderId);
                if (orderEntity.F_OrderState == 7)
                    AddOrderBookRecord(checkEntity);
            }
        }

        public void CheckOrderPrice(int ApplyType, string F_CheckId, int F_State, string F_CheckUserId, string F_FlowId, string F_OrderId, string F_No)
        {
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            List<string> list = new List<string>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                MessageNoticeEntity message = new MessageNoticeEntity();
                message.Create();
                message.F_IsRead = 0;
                message.F_MessageType = 1;
                message.F_MessageWay = 1;
                message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                if (F_State == 1)
                {
                    message.F_MessageContent = "场地报价单申请审核通过";
                }
                else
                {
                    message.F_MessageContent = "场地报价单申请驳回";
                }

                var result = GetListForOrderintention(F_OrderId, F_No);
                for (int i = 0; i < result.Count; i++)
                {
                    ClientOrderintentionEntity entity = result[i];
                    entity.F_State = F_State;
                    entity.Modify(entity.F_Id);
                    db.Update<ClientOrderintentionEntity>(entity);
                    list.Add(entity.F_SiteId);
                }

                db.Insert<MessageNoticeEntity>(message);
                checkEntity.F_State = F_State;
                checkEntity.Modify(F_CheckId);
                db.Update<CheckRecordEntity>(checkEntity);
                db.Commit();
            }

            OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, String.Join(",", list), F_State);
        }

        public void CheckDbOrderPrice(int ApplyType, string F_CheckId, int F_State, string F_CheckUserId, string F_FlowId, string F_OrderId, string F_No)
        {
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            List<string> list = new List<string>();
            using (var db = new RepositoryBase().BeginTrans())
            {
                MessageNoticeEntity message = new MessageNoticeEntity();
                message.Create();
                message.F_IsRead = 0;
                message.F_MessageType = 1;
                message.F_MessageWay = 1;
                message.F_ReceiveUserId = checkEntity.F_ApplyUserId;
                if (F_State == 1)
                {
                    message.F_MessageContent = "场地报价单申请审核通过";

                }
                else
                {
                    message.F_MessageContent = "场地报价单申请驳回";
                }

                var result = GetListForOrderpricetalks(F_OrderId, F_No);
                for (int i = 0; i < result.Count; i++)
                {
                    ClientOrderpricetalksEntity entity = result[i];
                    entity.F_State = F_State;
                    entity.Modify(entity.F_Id);
                    db.Update<ClientOrderpricetalksEntity>(entity);
                    list.Add(entity.F_SiteId);
                }

                db.Insert<MessageNoticeEntity>(message);
                checkEntity.F_State = F_State;
                checkEntity.Modify(F_CheckId);
                db.Update<CheckRecordEntity>(checkEntity);
                db.Commit();
            }

            OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, F_CheckId, checkEntity.F_No, checkEntity.F_OrderState, String.Join(",", list), F_State);
        }
        #endregion

        #region 公海订单审核
        public void SubmitCheckHighSea(string F_Id, string F_IsCheck)
        {
            ClientOrderEntity orderEntity = orderRepository.FindEntity(F_Id);
            if (F_IsCheck == "1")
            {
                orderEntity.F_IsCheck = 1;
                orderEntity.F_OrderEnvironment = 1;
                orderRepository.Update(orderEntity);
            }
            else
            {
                try
                {
                    using (var db = new RepositoryBase())
                    {
                        string strsql = "update Site_Client_Order set F_IsCheck=null,F_FlowUserId=null where F_Id='" + F_Id + "'";
                        db.ExecuteSql(strsql);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
        #endregion


        #region 场地带看

        /// <summary>
        /// 获取场地带看详情列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<OrderTakelookDetailViewModel> GetOrderTakelookDetailViewModels(Pagination pagination, string orderId, string F_CheckUserId, string F_No)
        {
            var dtoGroups = clientOrdertakelookDetailRepository.GetClientOrdertakelookDetailDtos(pagination, orderId, F_CheckUserId, F_No).GroupBy(x => x.F_OrderTakelookId);
            var bhly = itemsDetailApp.GetItemList("bhly");
            var vms = new List<OrderTakelookDetailViewModel>();
            var times = 1;  //次数

            foreach (var group in dtoGroups)
            {
                var vm = new OrderTakelookDetailViewModel();

                foreach (var entity in group)
                {
                    if (times == 1)
                    {
                        times++;

                        vm.F_SiteName = entity.F_SiteName;
                        vm.F_OrderId = entity.F_OrderId;
                        vm.F_OrderTakelookId = entity.F_OrderTakelookId;
                        vm.F_State = entity.F_State ?? 0;
                        vm.F_SpaceName = entity.F_SpaceName;
                        vm.F_Reason = bhly.FirstOrDefault(x => x.F_ItemCode == entity.F_Reason.ToString())?.F_ItemName;
                        vm.F_Remark = entity.F_Remark;
                    }

                    var json = entity.F_Source.ToObject<dynamic>();

                    switch (entity.F_SourceType)
                    {
                        case 1:
                            vm.F_LookTime = $"{json.startTime} ~ {json.endTime}";
                            break;
                        case 2:
                            vm.F_CarName = json.carName;
                            break;
                        case 3:
                            vm.F_UserName = json.userName;
                            break;
                        case null:
                        default:
                            break;
                    }
                }

                vms.Add(vm);

                times = 1;
            }

            return vms;
        }

        /// <summary>
        /// 确认带看
        /// </summary>
        /// <param name="orderTakelookId"></param>
        /// <param name="takeLookState"></param>
        /// <param name="reason"></param>
        /// <param name="remark"></param>
        /// <param name="checkId"></param>
        public void ConfirmTakeLook(string orderTakelookId, int takeLookState, int reason, string remark, string checkId, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            var entity = clientOrdertakelookRepository.FindEntity(orderTakelookId);

            if (entity == null) return;

            entity.Modify(orderTakelookId);
            entity.F_State = takeLookState;
            entity.F_Reason = reason;
            entity.F_Remark = remark;

            var checkEntity = checkRepository.FindEntity(checkId);
            var message = CreateDefaultMessageNotice(checkEntity.F_ApplyUserId, takeLookState == 1 ? "已确认带看场地" : "已驳回");

            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                mappingEntity.Create();
                mappingEntity.F_ApplyType = ApplyType;
                mappingEntity.F_DetailId = orderTakelookId;
                mappingEntity.F_State = takeLookState;
                mappingEntity.F_Reason = reason;
                mappingEntity.F_Remark = remark;
                mappingEntity.F_CheckUserId = F_CheckUserId;
                db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                db.Insert(message);
                entity.Modify(orderTakelookId);
                db.Update(entity);

                db.Commit();
            }

            var orderTakelooks = clientOrdertakelookRepository.IQueryable(x => (x.F_DeleteMark == null || x.F_DeleteMark == false) && x.F_OrderId == checkEntity.F_OrderId).ToList();
            //if (orderTakelooks.Any(x => x.F_State == 0 || x.F_State == null)) return;
            var yesTakeLooks = (from p in orderTakelooks where p.F_State == 1 select p).ToList().Count;
            var noTakeLooks = (from p in orderTakelooks where p.F_State == 2 select p).ToList().Count;
            if (orderTakelooks.Count != (noTakeLooks + yesTakeLooks))
            {
                return;
            }

            message.Create();

            if (orderTakelooks.Count(x => x.F_State == 2) == orderTakelooks.Count())
            {
                checkEntity.F_State = 0;
                message.F_MessageContent = "场地带看审核驳回";
            }
            else
            {
                checkEntity.F_State = 1;
                message.F_MessageContent = "场地带看审核通过";
            }

            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Insert(message);
                checkEntity.Modify(checkId);
                db.Update(checkEntity);

                db.Commit();
            }
            OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, takeLookState);
        }

        #endregion 场地带看

        #region 场地预定

        /// <summary>
        /// 获取场地预定视图模型集合
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<ClientOrderReserveViewModel> GetOrderReserveViewModelViewModels(Pagination pagination, string orderId, string F_CheckUserId, string F_No)
        {
            var dtos = clientOrderReserveRepository.GetClientOrderReserveDtos(pagination, orderId, F_CheckUserId, F_No);
            var vms = new List<ClientOrderReserveViewModel>();
            var bhly = itemsDetailApp.GetItemList("bhly");

            foreach (var dto in dtos)
            {
                vms.Add(ToClientOrderReserveViewModel(dto));
            }

            return vms;

            //转换成场地预定视图模型
            ClientOrderReserveViewModel ToClientOrderReserveViewModel(ClientOrderReserveDto dto)
            {
                var vm = new ClientOrderReserveViewModel()
                {
                    F_OrderReserveId = dto.F_Id,
                    F_OrderId = dto.F_OrderId,
                    F_Reason = dto.F_Reason == null
                        ? null
                        : bhly.FirstOrDefault(x => x.F_ItemCode == dto.F_Reason.ToString())?.F_ItemName,
                    F_Remark = dto.F_Remark,
                    F_ReserveTime = dto.F_ReserveTime?.ToString(),
                    F_SiteName = dto.F_SiteName,
                    F_SpaceName = dto.F_SpaceName,
                    F_State = dto.F_State?.ToString(),
                    StartingAndEndingDate = $"{(dto.F_StartDate == null ? "" : dto.F_StartDate.ToString())} ~ {(dto.F_EndDate == null ? "" : dto.F_EndDate.ToString())}",
                    F_StateDesc = GetStateDesc(dto.F_State)
                };

                return vm;
            }
        }

        /// <summary>
        /// 确认场地预定
        /// </summary>
        /// <param name="orderReserveId"></param>
        /// <param name="state"></param>
        /// <param name="reason"></param>
        /// <param name="remark"></param>
        /// <param name="checkId"></param>
        public void ConfirmReserve(string orderReserveId, int state, int reason, string remark, string checkId, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            var entity = clientOrderReserveRepository.FindEntity(orderReserveId);
            if (entity == null) return;

            entity.Modify(orderReserveId);
            entity.F_State = state;
            entity.F_Reason = reason;
            entity.F_Remark = remark;

            var checkEntity = checkRepository.FindEntity(checkId);
            var message = CreateDefaultMessageNotice(checkEntity.F_ApplyUserId, state == 1 ? "已确认场地预定" : "已驳回");

            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                mappingEntity.Create();
                mappingEntity.F_ApplyType = ApplyType;
                mappingEntity.F_DetailId = orderReserveId;
                mappingEntity.F_State = state;
                mappingEntity.F_CheckUserId = F_CheckUserId;
                db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                db.Insert(message);

                entity.Modify(orderReserveId);
                db.Update(entity);

                db.Commit();
            }

            var orderReserves = clientOrderReserveRepository.IQueryable(x =>
                (x.F_DeleteMark == null || x.F_DeleteMark == false) && x.F_OrderId == checkEntity.F_OrderId).ToList();
            if (orderReserves.Any(x => x.F_State == 0)) return;

            message.Create();

            if (orderReserves.Count(x => x.F_State == 2) == orderReserves.Count())
            {
                checkEntity.F_State = 0;
                message.F_MessageContent = "场地预定审核驳回";
            }
            else
            {
                checkEntity.F_State = 1;
                message.F_MessageContent = "场地预定审核通过";
            }

            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Insert(message);
                checkEntity.Modify(checkId);
                db.Update(checkEntity);

                db.Commit();
            }
            OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, state);
        }

        #endregion 场地预定

        #region 合同审核

        /// <summary>
        /// 获取合同审核视图模型集合
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<ClientOrderSignContractViewModel> GetOrderSignContractViewModelViewModels(Pagination pagination, string orderId, string userId, string F_No)
        {
            var dtos = clientOrderSignContractRepository.GetClientOrderSignContractDtos(pagination, orderId, userId, F_No);
            var vms = new List<ClientOrderSignContractViewModel>();
            var bhly = itemsDetailApp.GetItemList("bhly");

            foreach (var dto in dtos)
            {
                vms.Add(ToClientOrderSignContractViewModel(dto));
            }

            return vms;

            //转换成合同审核视图模型
            ClientOrderSignContractViewModel ToClientOrderSignContractViewModel(ClientOrderSignContractDto dto)
            {
                var vm = new ClientOrderSignContractViewModel()
                {
                    F_OrderSignContractId = dto.F_Id,
                    F_OrderId = dto.F_OrderId,
                    F_Reason = dto.F_Reason == null
                        ? null
                        : bhly.FirstOrDefault(x => x.F_ItemCode == dto.F_Reason.ToString())?.F_ItemName,
                    F_Remark = dto.F_Remark,
                    //F_SignContractTime = dto.F_SignContractTime?.ToString(),
                    F_SiteName = dto.F_SiteName,
                    F_SpaceName = dto.F_SpaceName,
                    F_State = dto.F_State?.ToString(),
                    F_FileName = dto.F_FileName,
                    F_FilePath = dto.F_FilePath,
                    StartingAndEndingDate = $"{(dto.F_StartDate == null ? "" : dto.F_StartDate.ToString())} ~ {(dto.F_EndDate == null ? "" : dto.F_EndDate.ToString())}",
                    F_StateDesc = GetStateDesc(dto.F_State)
                };

                return vm;
            }
        }

        /// <summary>
        /// 确认合同审核
        /// </summary>
        /// <param name="orderSignContractId"></param>
        /// <param name="state"></param>
        /// <param name="reason"></param>
        /// <param name="remark"></param>
        /// <param name="checkId"></param>
        public void ConfirmSignContract(string orderSignContractId, int state, string remark, string checkId, string F_FlowId, int ApplyType, string F_CheckUserId)
        {
            var entity = clientOrderSignContractRepository.FindEntity(orderSignContractId);
            if (entity == null) return;

            entity.Modify(orderSignContractId);
            entity.F_State = state;
            //entity.F_Reason = reason;
            entity.F_Remark = remark;

            var checkEntity = checkRepository.FindEntity(checkId);
            var message = CreateDefaultMessageNotice(checkEntity.F_ApplyUserId, state == 1 ? "已确认合同审核" : "已驳回");

            using (var db = new RepositoryBase().BeginTrans())
            {
                SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                mappingEntity.Create();
                mappingEntity.F_ApplyType = ApplyType;
                mappingEntity.F_DetailId = orderSignContractId;
                mappingEntity.F_State = state;
                mappingEntity.F_CheckUserId = F_CheckUserId;
                db.Insert<SiteClientOrderMappingEntity>(mappingEntity);

                db.Insert(message);

                entity.Modify(orderSignContractId);
                db.Update(entity);

                db.Commit();
            }

            var orderSignContracts = clientOrderSignContractRepository.IQueryable(x =>
                (x.F_DeleteMark == null || x.F_DeleteMark == false) && x.F_OrderId == checkEntity.F_OrderId).ToList();

            if (orderSignContracts.Any(x => x.F_State == 0)) return;

            message.Create();

            if (orderSignContracts.Count(x => x.F_State == 2) == orderSignContracts.Count())
            {
                checkEntity.F_State = 0;
                message.F_MessageContent = "合同审核审核驳回";
            }
            else
            {
                checkEntity.F_State = 1;
                message.F_MessageContent = "合同审核审核通过";
            }

            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Insert(message);

                checkEntity.Modify(checkId);
                db.Update(checkEntity);

                db.Commit();
            }
            OpreationFlowProcess(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState);
            SendMessage.Send(F_FlowId, ApplyType, checkEntity.F_OrderId, checkId, checkEntity.F_No, checkEntity.F_OrderState, entity.F_SiteId, state);

            if (state == 1)
            {
                ClientOrderEntity orderEntity = orderRepository.FindEntity(checkEntity.F_OrderId);
                if (orderEntity.F_OrderState == 8)
                    EditOrderBookRecord(checkEntity);
            }
        }

        #endregion 合同审核

        #region private methods

        /// <summary>
        /// 创建一条默认消息
        /// </summary>
        /// <returns></returns>
        private static MessageNoticeEntity CreateDefaultMessageNotice(string receiveUserId, string content)
        {
            var message = new MessageNoticeEntity
            {
                F_IsRead = 0,
                F_MessageType = 1,
                F_MessageWay = 1,
                F_ReceiveUserId = receiveUserId,
                F_MessageContent = content
            };

            message.Create();
            return message;
        }

        //获取状态描述
        private static string GetStateDesc(int? state)
        {
            string stateDesc = null;

            switch (state)
            {
                case 0:
                    stateDesc = "未审核";
                    break;
                case 1:
                    stateDesc = "同意";
                    break;
                case 2:
                    stateDesc = "驳回";
                    break;
                case null:
                default:
                    break;
            }

            return stateDesc;
        }

        #endregion private methods

        #region 流程处理
        /// <summary>
        /// 审批顺序
        /// </summary>
        /// <param name="F_FlowId"></param>
        /// <param name="ApplyType"></param>
        /// <param name="F_CheckUserId"></param>
        /// <param name="OrderId"></param>
        /// <param name="F_No"></param>
        /// <returns></returns>
        public bool OpreationFlowCheck(string F_FlowId, int ApplyType, string F_CheckId)
        {
            SysWorkFlowDetailEntity entity = GetSysWorkFlowDetailEntity(F_FlowId, ApplyType);
            CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
            if (entity.F_ApprovalNo == 1)
            {
                List<CheckRecordEntity> checkList = GetCheckRecordEntityList(checkEntity.F_OrderId, ApplyType, checkEntity.F_No);
                var Check = checkList.Where(t => t.F_State == null).OrderBy(t => t.F_CreatorTime).FirstOrDefault();
                if (Check != null)
                {
                    if (Check.F_CheckUserId != checkEntity.F_CheckUserId)
                        return false;
                }
            }
            return true;
        }

        public void OpreationFlowProcess(string F_FlowId, int ApplyType, string OrderId, string F_CheckId, string F_No, int ck_F_OrderState)
        {
            // 更新状态为成功，让用户手动跳转 2018.04.18 gaotang
            var allSelfOrderState = new int?[] { 1/*场地推荐状态*/, 2/*带看场地状态*/ };

            SysWorkFlowDetailEntity entity = GetSysWorkFlowDetailEntity(F_FlowId, ApplyType);
            List<CheckRecordEntity> checkList = GetCheckRecordEntityList(OrderId, ApplyType, F_No);


            //所有人同意才能通过
            if (entity.F_OpreationStrategy == 2)
            {
                var noCount = (from p in checkList where p.F_State == 0 select p).Count();
                var successCount = (from p in checkList where p.F_State == 1 select p).Count();
                //只要有人不同意就处理剩下没有处理的全部驳回
                if (noCount > 0 && checkList.Count > 1)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        db.ExecuteSql("update Sys_CheckRecord set F_state=0 where F_state is null and F_OrderId='" + OrderId + "' and F_ApplyType=" + ApplyType + " and F_FlowId='" + F_FlowId + "' and F_No='" + F_No + "'");
                        //List<OrderCheckDetailModel> list = GetDetailList(OrderId, ApplyType, F_CheckId);
                        //for (int i = 0; i < list.Count; i++)
                        //{
                        //    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                        //    mappingEntity.Create();
                        //    mappingEntity.F_ApplyType = ApplyType;
                        //    mappingEntity.F_DetailId = list[i].F_Id;
                        //    mappingEntity.F_State = 0;
                        //    mappingEntity.F_CheckUserId = list[i].F_CheckUserId;
                        //    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                        //}

                        ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);
                        if (entity.F_ReturnType == 1)
                        {
                            //orderEntity.F_OrderState = orderEntity.F_OrderState - 1;
                            //orderEntity.F_OrderStateProcess = -1;
                        }
                        else if (entity.F_ReturnType == 2)
                        {
                            orderEntity.F_OrderState = 1;
                            orderEntity.F_OrderStateProcess = -1;
                        }

                        orderEntity.Modify(OrderId);
                        db.Update<ClientOrderEntity>(orderEntity);
                        db.Commit();
                    }
                }
                else if (checkList.Count == 1 && noCount > 0)
                {
                    //using (var db = new RepositoryBase().BeginTrans())
                    //{
                    //    ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);
                    //    orderEntity.F_OrderState = orderEntity.F_OrderState - 1;
                    //    orderEntity.F_OrderStateProcess = -1;

                    //    orderEntity.Modify(OrderId);
                    //    db.Update<ClientOrderEntity>(orderEntity);
                    //    db.Commit();
                    //}
                }
                else if (checkList.Count == 1 && noCount == 0)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);

                        if (allSelfOrderState.Contains(orderEntity.F_OrderState))
                        {
                            orderEntity.F_OrderStateProcess = 1;
                        }
                        else
                        {
                            if (ck_F_OrderState == orderEntity.F_OrderState)
                            {
                                orderEntity.F_OrderState = orderEntity.F_OrderState + 1;
                                orderEntity.F_OrderStateProcess = -1;
                            }
                        }

                        orderEntity.Modify(OrderId);
                        db.Update<ClientOrderEntity>(orderEntity);
                        db.Commit();
                    }
                }
                else if (checkList.Count == successCount && noCount == 0)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);

                        if (allSelfOrderState.Contains(orderEntity.F_OrderState))
                        {
                            orderEntity.F_OrderStateProcess = 1;
                        }
                        else
                        {
                            if (ck_F_OrderState == orderEntity.F_OrderState)
                            {
                                orderEntity.F_OrderState = orderEntity.F_OrderState + 1;
                                orderEntity.F_OrderStateProcess = -1;
                            }
                        }

                        orderEntity.Modify(OrderId);
                        db.Update<ClientOrderEntity>(orderEntity);
                        db.Commit();
                    }
                }
            }//一人同意即可
            else if (entity.F_OpreationStrategy == 1)
            {
                var count = (from p in checkList where p.F_State == 1 select p).Count();
                //只要有人同意就处理剩下没有处理的全部审批                
                if (checkList.Count > 1 && count > 0)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        db.ExecuteSql("update Sys_CheckRecord set F_state=1 where F_state is null and F_OrderId='" + OrderId + "' and F_ApplyType=" + ApplyType + " and F_FlowId='" + F_FlowId + "' and F_No='" + F_No + "'");
                        //List<OrderCheckDetailModel> list = GetDetailList(OrderId, ApplyType, F_CheckId,F_No);
                        //for (int i = 0; i < list.Count; i++)
                        //{
                        //    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                        //    mappingEntity.Create();
                        //    mappingEntity.F_ApplyType = ApplyType;
                        //    mappingEntity.F_DetailId = list[i].F_Id;
                        //    mappingEntity.F_State = 1;
                        //    mappingEntity.F_CheckUserId = list[i].F_CheckUserId;
                        //    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                        //}
                        ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);
                        if (allSelfOrderState.Contains(orderEntity.F_OrderState))
                        {
                            orderEntity.F_OrderStateProcess = 1;
                        }
                        else
                        {
                            if (ck_F_OrderState == orderEntity.F_OrderState)
                            {
                                orderEntity.F_OrderState = orderEntity.F_OrderState + 1;
                                orderEntity.F_OrderStateProcess = -1;
                            }
                        }

                        orderEntity.Modify(OrderId);
                        db.Update<ClientOrderEntity>(orderEntity);
                        db.Commit();
                    }
                }
                else if (checkList.Count == 1 && count > 0)
                {
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);
                        if (allSelfOrderState.Contains(orderEntity.F_OrderState))
                        {
                            orderEntity.F_OrderStateProcess = 1;
                        }
                        else
                        {
                            if (ck_F_OrderState == orderEntity.F_OrderState)
                            {
                                orderEntity.F_OrderState = orderEntity.F_OrderState + 1;
                                orderEntity.F_OrderStateProcess = -1;
                            }

                        }

                        orderEntity.Modify(OrderId);
                        db.Update<ClientOrderEntity>(orderEntity);
                        db.Commit();
                    }
                }
                else if (checkList.Count == 1 && count == 0)
                {
                    //using (var db = new RepositoryBase().BeginTrans())
                    //{
                    //    ClientOrderEntity orderEntity = orderRepository.FindEntity(OrderId);
                    //    orderEntity.F_OrderState = orderEntity.F_OrderState - 1;
                    //    orderEntity.F_OrderStateProcess = -1;

                    //    orderEntity.Modify(OrderId);
                    //    db.Update<ClientOrderEntity>(orderEntity);
                    //    db.Commit();
                    //}
                }
            }
        }

        public List<OrderCheckDetailModel> GetDetailList(string OrderId, int F_ApplyType, string F_CheckId, string F_No)
        {
            List<OrderCheckDetailModel> result = new List<OrderCheckDetailModel>();
            using (var db = new RepositoryBase())
            {
                string strSql = "";
                if (F_ApplyType == 1)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderRecommend b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 2)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderTakelook b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 3)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderIntention b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 4)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderPriceTalks b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 5)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderPriceDetail b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 6)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderReserve b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 7)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderUsing b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                else if (F_ApplyType == 8)
                {
                    strSql = @"select distinct a.F_Id,a.F_CheckUserId from Sys_CheckRecord a
                                inner join Site_Client_OrderSignContract b on a.F_OrderId = b.F_OrderId
                                left join Site_Client_OrderMapping c on c.F_DetailId = b.F_Id and a.F_CheckUserId = c.F_CheckUserId and c.F_State is null
                                where a.F_OrderId = '" + OrderId + "' and a.F_ApplyType = " + F_ApplyType + " and a.F_Id not in('" + F_CheckId + "')  and a.F_No='" + F_No + "'";
                }
                result = db.FindList<OrderCheckDetailModel>(strSql);
            }
            return result;
        }

        public List<CheckRecordEntity> GetCheckRecordEntityList(string OrderId, int F_ApplyType, string F_No)
        {
            List<CheckRecordEntity> result = new List<CheckRecordEntity>();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Sys_CheckRecord a where a.F_OrderId='" + OrderId + "' and a.F_ApplyType=" + F_ApplyType + " and a.F_No='" + F_No + "'";
                result = db.FindList<CheckRecordEntity>(strSql);
            }
            return result;
        }

        //获取流程信息
        public SysWorkFlowDetailEntity GetSysWorkFlowDetailEntity(string F_FlowId, int ApplyType)
        {
            SysWorkFlowDetailEntity entity = new SysWorkFlowDetailEntity();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Sys_WorkFlowDetail a where a.F_WorkFlowId='" + F_FlowId + "' and a.F_WorkFlowNo=" + ApplyType + "";
                entity = db.FindList<SysWorkFlowDetailEntity>(strSql).FirstOrDefault();
            }
            return entity;
        }
        #endregion

        #region 用印审批
        public OrderUsingModel GetOrderUsing(string F_CheckId, string F_OrderId)
        {
            //CheckRecordEntity entity = checkRepository.FindEntity(F_CheckId);
            List<OrderUsingDemandModel> demand = new List<OrderUsingDemandModel>();
            List<ClientOrderusingEntity> usingBusniess = new List<ClientOrderusingEntity>();
            List<ClientOrderusingpriceEntity> usingPrices = new List<ClientOrderusingpriceEntity>();
            List<OrderSignViewModel> signRecord = new List<OrderSignViewModel>();
            using (var db = new RepositoryBase())
            {
                string strSql = @"select distinct a.F_Id,b.F_ActivityTheme,date_format(b.F_ActivityStartDate, '%Y-%m-%d') F_ActivityStartDate,
                date_format(b.F_ActivityEndDate, '%Y-%m-%d') F_ActivityEndDate,c.title SiteName,b.F_ActivityCityId,d.F_ClientName,ifnull(h.name,'') SupplierName,
                d.F_IndustryId,f.F_BrandName,b.F_ActivityType
                from Site_Client_Order a 
                inner join Site_Clients_ProjectByDemand b on a.F_DemandId=b.F_Id
                inner join Site_Clients d on b.F_ClientId=d.F_Id
                left join Site_Clients_BrandsMapping e on e.F_DemandId=b.F_Id
                left join Site_Clients_Brands f on f.F_Id=e.F_BrandId
                left join Site_Client_OrderReserve g on a.F_Id=g.F_OrderId and g.F_State=1
                inner join Sys_CheckRecord j on j.F_OrderId=a.F_Id and j.F_ApplyType=6
                inner join SL_Site c on c.F_Id=g.F_SiteId
                left join SL_Supplier h on h.F_Id=c.F_SupplierId
                where a.F_Id='" + F_OrderId + "'";
                demand = db.FindList<OrderUsingDemandModel>(strSql);
            }

            using (var db = new RepositoryBase())
            {
                string strSql = @"select a.F_Id,a.F_No,a.F_OrderId,ifnull(a.F_IncomeCash,0) F_IncomeCash,a.F_FeeType,a.F_FeeName,ifnull(a.F_SpendCash,0) F_SpendCash,
                                ifnull(a.F_Tax,0) F_Tax,ifnull(a.F_AfterTaxProfit,0) F_AfterTaxProfit,ifnull(a.F_ManagerFee,0) F_ManagerFee,ifnull(a.F_ProfitMargin,0) F_ProfitMargin,a.F_CreatorTime
                                ,a.F_CreatorUserId,a.F_LastModifyTime,a.F_LastModifyUserId,a.F_DeleteMark,a.F_DeleteTime,a.F_DeleteUserId from Site_Client_OrderUsing a 
                                where a.F_OrderId='" + F_OrderId + "' order by a.F_FeeName asc,a.F_FeeType asc";
                usingBusniess = db.FindList<ClientOrderusingEntity>(strSql);
            }

            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from Site_Client_OrderUsingPrice a where a.F_OrderId='" + F_OrderId + "' order by a.F_InOutType asc,a.F_No asc,a.F_InOutDate asc";
                usingPrices = db.FindList<ClientOrderusingpriceEntity>(strSql);
            }
            using (var db = new RepositoryBase())
            {
                string strSql = $@"select 
		                                ifnull(t2.F_RealName,'') as signname,
		                                ifnull(t3.F_FullName,'') as signorganize,
		                                ifnull(t.F_Note,'') as F_Note 
	                                from Sys_SignRecord t 
	                                left join Sys_User t2 on t.F_ConunTerisnUserId=t2.F_Id
	                                left join Sys_Organize t3 on t2.F_DepartmentId=t3.F_Id
	                                where t.F_OrderId='{F_OrderId}'";
                signRecord = db.FindList<OrderSignViewModel>(strSql);
            }
            OrderUsingModel usingmodel = new OrderUsingModel()
            {
                usingDemand = demand,
                usingBusniess = usingBusniess,
                usingPrices = usingPrices,
                signRecord = signRecord
            };

            return usingmodel;
        }

        #endregion

        #region 订单签约记录
        public void AddOrderBookRecord(CheckRecordEntity check)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                string sqlStr = $@"select 
	                                    t.F_FeeName,
	                                    ifnull(sum(t.F_IncomeCash),0) IncomeCash,
	                                    ifnull(sum(t.F_SpendCash),0) SpendCash,
	                                    ifnull(sum(t.F_Tax),0) Tax,
	                                    ifnull(sum(t.F_AfterTaxProfit),0) AfterTaxProfit,
	                                    ifnull(avg(t.F_ProfitMargin),0) ProfitMargin
	                                    from Site_Client_OrderUsing t	
                                    where t.F_OrderId='{check.F_OrderId}' and t.F_FeeType='1'
                                    group by t.F_FeeName";
                string sqlStr_ManagerFee = $@"select
	                                                ifnull(t.F_IncomeCash,0) IncomeCash
	                                                from Site_Client_OrderUsing t	
                                                where t.F_OrderId='{check.F_OrderId}' and 
                                                      (t.F_FeeType!='1' and t.F_FeeType!='13' and t.F_FeeType!='14')";
                var ManagerFee = db.FindList<OrderUsingByRecord>(sqlStr_ManagerFee).Sum(a => a.IncomeCash);

                string sqlStr_Rebate = $@"select 
	                                    t.F_FeeName,t.F_FeeType,
	                                    ifnull(sum(t.F_IncomeCash),0) IncomeCash	                                  
	                                    from Site_Client_OrderUsing t	
                                    where t.F_OrderId='{check.F_OrderId}'
												 and (t.F_FeeType='13' or t.F_FeeType='14')
                                    group by t.F_FeeName,t.F_FeeType";
                var RebateList = db.FindList<OrderUsingByRecord>(sqlStr_Rebate);

                string sqlStr_Price = $@"select 
		                                        F_InOutType as F_FeeType,
		                                        sum(F_InOutCash) F_InOutCash as IncomeCash
	                                        from Site_Client_OrderUsingPrice t
	                                        where t.F_OrderId='{check.F_OrderId}'
	                                        group by F_InOutType";
                var PriceList = db.FindList<OrderUsingByRecord>(sqlStr_Price);

                var list = db.FindList<OrderUsingByRecord>(sqlStr);
                foreach (var item in list)
                {
                    var record = new ClientOrderBookRecordEntity();
                    record.Create();
                    record.F_OrderId = check.F_OrderId;
                    record.F_SiteRent = item.IncomeCash;
                    record.F_SiteExpend = item.SpendCash;
                    record.F_TaxRebate = item.Tax;
                    record.F_Profit = item.AfterTaxProfit;
                    record.F_ProfitMargin = item.ProfitMargin;
                    record.F_State = 0;
                    record.F_SiteRebate = RebateList.Where(a => a.F_FeeName == item.F_FeeName && a.F_FeeType == 13).Sum(a => a.IncomeCash);
                    record.F_ClientRebate = RebateList.Where(a => a.F_FeeName == item.F_FeeName && a.F_FeeType == 14).Sum(a => a.IncomeCash);
                    record.F_MatingRent = ManagerFee;
                    record.F_ReserveCash = PriceList.Where(a => a.F_FeeType == 2).Sum(a => a.IncomeCash);
                    record.F_Deposit = PriceList.Where(a => a.F_FeeType == 3).Sum(a => a.IncomeCash);
                    db.Insert<ClientOrderBookRecordEntity>(record);
                }
                db.Commit();
            }
        }

        public void EditOrderBookRecord(CheckRecordEntity check)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                string sqlStr = $@"SELECT * FROM Site_Client_OrderBookRecord t where t.F_OrderId='{check.F_OrderId}'";
                var list = db.FindList<ClientOrderBookRecordEntity>(sqlStr);
                foreach (var item in list)
                {
                    item.F_SigningDate = DateTime.Now;
                    item.F_State = 1;
                    db.Update<ClientOrderBookRecordEntity>(item);
                }
                db.Commit();
            }
        }
        #endregion

        #region 会签

        /// <summary>
        /// 添加会签记录
        /// </summary>
        /// <returns></returns>
        public void OpreationSignRecord(string F_FlowId, int ApplyType, string F_CheckId)
        {
            SysWorkFlowDetailEntity entity = GetSysWorkFlowDetailEntity(F_FlowId, ApplyType);
            if (entity.F_IsCountersign == 1)
            {
                if (!entity.F_ConunTerisnUserId.IsNullOrEmpty())
                {
                    CheckRecordEntity checkEntity = checkRepository.FindEntity(F_CheckId);
                    List<CheckRecordEntity> checkList = GetCheckRecordEntityList(checkEntity.F_OrderId, ApplyType, checkEntity.F_No);
                    var OpUserIds = entity.F_OpreationUserId.Split(',');
                    var opSignIds = entity.F_ConunTerisnUserId.Split(',');
                    if (OpUserIds.Length < entity.F_CountersignNum)
                        return;

                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        FlowManageApp app = new FlowManageApp();
                        var result = app.GetCheckUserId(entity.F_WorkFlowNo ?? 0, entity.F_OperationPersonType, db, OpUserIds[entity.F_CountersignNum - 1 ?? 0], checkEntity.F_OrderId, checkEntity.F_No);

                        if (result.Count(t => t.Item1 == checkEntity.F_CheckUserId) > 0)
                        {
                            foreach (var item in opSignIds)
                            {
                                if (entity.F_CounTersignType == "1")
                                {
                                    var User = db.FindEntity<UserEntity>(item);
                                    if (User != null)
                                    {
                                        var SignRecord = new SignRecordEntity()
                                        {
                                            F_OrderId = checkEntity.F_OrderId,
                                            F_No = checkEntity.F_No,
                                            F_FlowId = checkEntity.F_FlowId,
                                            F_ApplyType = checkEntity.F_ApplyType,
                                            F_ConunTerisnUserId = User.F_Id,
                                            F_CheckContent = checkEntity.F_CheckContent,
                                            F_ApplyUserId = checkEntity.F_ApplyUserId
                                        };
                                        SignRecord.Create();
                                        db.Insert<SignRecordEntity>(SignRecord);
                                    }
                                }
                                if (entity.F_CounTersignType == "2")
                                {
                                    var User = db.FindEntity<UserEntity>(t => t.F_RoleId == item && t.F_EnabledMark == true);
                                    if (User != null)
                                    {
                                        var SignRecord = new SignRecordEntity()
                                        {
                                            F_OrderId = checkEntity.F_OrderId,
                                            F_No = checkEntity.F_No,
                                            F_FlowId = checkEntity.F_FlowId,
                                            F_ApplyType = checkEntity.F_ApplyType,
                                            F_ConunTerisnUserId = User.F_Id,
                                            F_CheckContent = checkEntity.F_CheckContent,
                                            F_ApplyUserId = checkEntity.F_ApplyUserId
                                        };
                                        SignRecord.Create();
                                        db.Insert<SignRecordEntity>(SignRecord);
                                    }
                                }
                            }
                            db.Commit();
                        }
                    }
                }
            }
        }

        public List<OrderSignViewModel> GetOrderSignList(Pagination pagination, string userId)
        {
            List<OrderSignViewModel> list = new List<OrderSignViewModel>();
            string sqlwhere = userId.IsNullOrEmpty() ? "" : " AND t.F_ConunTerisnUserId=@userId";
            using (var db = new RepositoryBase())
            {
                string sql = @"SELECT 
                                        t.F_Id,        
	                                    t.F_OrderId,
	                                    t.F_No,
	                                    t.F_ApplyType,
	                                    t.F_CheckContent as content,
	                                    t5.F_ActivityTheme as theme,
	                                    t3.F_RealName as signname,
	                                    t4.F_FullName as signorganize,
	                                    t7.F_FullName as cityId,
	                                    t5.F_ActivityStartDate as time,
	                                    t6.F_RealName as checkname,
	                                    t8.F_FullName as checkorganize,
                                        t.F_Note
	                                FROM Sys_SignRecord t 
	                                INNER JOIN Site_Client_Order t2 ON t.F_OrderId=t2.F_Id
	                                LEFT JOIN Sys_User t3 ON t.F_ConunTerisnUserId=t3.F_Id
		                            LEFT JOIN Sys_Organize t4 on t3.F_DepartmentId=t4.F_Id	                               
	                                INNER JOIN Site_Clients_ProjectByDemand t5 on t2.F_DemandId=t5.F_Id
	                                LEFT JOIN Sys_User t6 ON t.F_ApplyUserId=t6.F_Id
	                                LEFT JOIN Sys_Organize t8 on t6.F_DepartmentId=t8.F_Id	       
                                    LEFT JOIN Sys_Area t7 ON t5.F_ActivityCityId=t7.F_Id
	                                WHERE 1=1 {0}";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@userId", userId)
                };
                sql = String.Format(sql, sqlwhere);
                list = db.FindList<OrderSignViewModel>(sql, parameter, pagination);
            }
            return list;
        }

        public void AddSignContent(string SignContent, string F_ID)
        {
            using (var db = new RepositoryBase())
            {
                var Sign = db.FindEntity<SignRecordEntity>(F_ID);
                Sign.F_Note = SignContent;
                Sign.Modify(F_ID);
                db.Update<SignRecordEntity>(Sign);
            }
        }
        #endregion
    }
}
